using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace CodeStory.WebControls
{
	[PersistChildren(false)]
	[ParseChildren(true)]
	[ToolboxData("<{0}:StateImageButton runat=server></{0}:StateImageButton>")]
	public class StateImageButton : ImageButton
	{
		[DefaultValue("")]
		public string State {
			get {
				object obj = ViewState["State"];
				return obj == null ? string.Empty : (string)obj;
			}
			set { ViewState["State"] = value; }
		}
		StateTemplateCollection _states;
		[PersistenceMode(PersistenceMode.InnerProperty)]
		public StateTemplateCollection ImageStates {
			get {
				if (_states == null) {
					_states = new StateTemplateCollection();
					if (IsTrackingViewState) {
						((IStateManager)_states).TrackViewState();
					}
				}
				return _states;
			}
		}

		protected override void AddAttributesToRender(HtmlTextWriter writer) {
			StateTemplate template = null;
			foreach (StateTemplate t in ImageStates) {
				if (string.Equals(State, t.State, StringComparison.OrdinalIgnoreCase)) {
					template = t;
					break;
				}
			}
			if (template != null) {
				ImageUrl = template.ImageUrl;
				BorderColor = template.BorderColor;
				BorderStyle = template.BorderStyle;
				BorderWidth = template.BorderWidth;
			}
			base.AddAttributesToRender(writer);
		}

		protected override void LoadViewState(object savedState) {
			if (savedState == null) return;
			Pair p = (Pair)savedState;
			base.LoadViewState(p.First);
			((IStateManager)ImageStates).LoadViewState(p.Second);
		}
		protected override object SaveViewState() {
			Pair p = new Pair();
			p.First = base.SaveViewState();
			if (_states != null) {
				p.Second = ((IStateManager)_states).SaveViewState();
			}
			if (p.First == null && p.Second == null) return null;
			return p;
		}
		protected override void TrackViewState() {
			base.TrackViewState();
			if (_states != null) {
				((IStateManager)_states).TrackViewState();
			}
		}
	}
}
